'use client'

import React, { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import {
    Card,
    Button,
    Typography,
    Space,
    Tag,
    Breadcrumb,
    Spin,
    Alert,
    Progress,
    Descriptions,
    Row,
    Col,
    Statistic,
    Tabs,
    Modal,
    message
} from 'antd'
import {
    ArrowLeftOutlined,
    PlayCircleOutlined,
    StopOutlined,
    DownloadOutlined,
    HomeOutlined,
    DatabaseOutlined,
    ExperimentOutlined,
    ClockCircleOutlined,
    CheckCircleOutlined,
    SettingOutlined,
    BarChartOutlined,
    FileTextOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons'
import { useTaskStore } from '@/stores/taskStore'
import { useImageStore } from '@/stores/imageStore'
import { useUIStore } from '@/stores/uiStore'
import { TaskParameterConfig } from '@/components/TaskParameterConfig'
import { TaskStatusDisplay } from '@/components/TaskStatusDisplay'
import { TaskResultDisplay } from '@/components/TaskResultDisplay'
import { Task, TaskParams, TaskConfig } from '@/types/task'
import { mockDatasets, mockTasks } from '@/utils/mockData'


const { Title, Text, Paragraph } = Typography

interface TaskExecutionProps {
    datasetId: string
    taskId: string
}

export const TaskExecution: React.FC<TaskExecutionProps> = ({ datasetId, taskId }) => {
    const router = useRouter()
    const {
        startTask,
        cancelTask,
        retryTask,
        taskStatuses,
        results,
        errors,
        isProcessing,
        loadTasks
    } = useTaskStore()
    const { setCurrentImage } = useImageStore()
    const { setViewerType, updateBreadcrumbs } = useUIStore()

    const [loading, setLoading] = useState(true)
    const [activeTab, setActiveTab] = useState('config')
    const [taskParameters, setTaskParameters] = useState<TaskParams>({})
    const [showCancelModal, setShowCancelModal] = useState(false)

    // 获取数据集和任务信息（使用模拟数据）
    const dataset = mockDatasets.find(d => d.id === datasetId)
    const task = mockTasks.find(t => t.id === taskId) as Task | undefined
    // const taskStatus = taskStatuses[taskId] // 暂时未使用
    const taskResult = results[taskId]
    // const taskError = errors[taskId] // 暂时未使用

    useEffect(() => {
        const initializeTask = async () => {
            setLoading(true)
            try {
                // 加载任务列表
                await loadTasks(datasetId)

                // 如果有数据集，设置查看器类型并加载示例图像
                if (dataset) {
                    setViewerType(dataset.type)
                    if (dataset.images.length > 0) {
                        setCurrentImage(dataset.images[0])
                    }
                }

                // 初始化任务参数
                if (task) {
                    setTaskParameters(task.config.parameters as TaskParams)
                }
            } catch (error) {
                console.error('Failed to initialize task:', error)
                message.error('初始化任务失败')
            } finally {
                setLoading(false)
            }
        }

        initializeTask()

        // 更新面包屑
        updateBreadcrumbs([
            { label: '首页', path: '/', isActive: false },
            { label: '数据集', path: `/dataset/${datasetId}`, isActive: false },
            { label: '任务执行', path: `/task/${datasetId}/${taskId}`, isActive: true }
        ])
    }, [datasetId, taskId, dataset, task, loadTasks])

    const handleStartTask = async () => {
        if (!task) return

        try {
            await startTask(taskId, taskParameters)
            message.success('任务已启动')
            setActiveTab('status')
        } catch (error) {
            console.error('Failed to start task:', error)
            message.error('启动任务失败')
        }
    }

    const handleCancelTask = async () => {
        try {
            await cancelTask(taskId)
            message.success('任务已取消')
            setShowCancelModal(false)
        } catch (error) {
            console.error('Failed to cancel task:', error)
            message.error('取消任务失败')
        }
    }

    const handleRetryTask = async () => {
        try {
            await retryTask(taskId)
            message.success('任务重试中')
            setActiveTab('status')
        } catch (error) {
            console.error('Failed to retry task:', error)
            message.error('重试任务失败')
        }
    }

    const handleParametersChange = (params: TaskParams) => {
        setTaskParameters(params)
    }

    const handleConfigSave = async (config: TaskConfig) => {
        try {
            // 这里应该调用更新任务配置的API
            message.success('配置已保存')
        } catch (error) {
            console.error('Failed to save config:', error)
            message.error('保存配置失败')
        }
    }

    const handleBackToDataset = () => {
        router.push(`/dataset/${datasetId}`)
    }

    const handleBackToHome = () => {
        router.push('/')
    }

    if (loading) {
        return (
            <div className="task-execution h-screen flex items-center justify-center">
                <div className="text-center">
                    <Spin size="large" />
                    <div className="mt-4">
                        <Text>正在初始化任务...</Text>
                    </div>
                </div>
            </div>
        )
    }

    if (!dataset || !task) {
        return (
            <div className="task-execution h-screen flex items-center justify-center">
                <Alert
                    message="任务未找到"
                    description="无法找到指定的数据集或任务"
                    type="error"
                    showIcon
                    action={
                        <Button type="primary" onClick={handleBackToHome}>
                            返回首页
                        </Button>
                    }
                />
            </div>
        )
    }

    return (
        <div className="task-execution min-h-screen bg-gray-50">
            {/* 头部导航 */}
            <div className="header bg-white shadow-sm border-b">
                <div className="max-w-7xl mx-auto px-4 py-4">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-4">
                            <Button
                                type="text"
                                icon={<ArrowLeftOutlined />}
                                onClick={handleBackToDataset}
                            >
                                返回数据集
                            </Button>
                            <Breadcrumb
                                items={[
                                    {
                                        href: '/',
                                        title: (
                                            <>
                                                <HomeOutlined />
                                                <span>首页</span>
                                            </>
                                        )
                                    },
                                    {
                                        href: `/dataset/${datasetId}`,
                                        title: (
                                            <>
                                                <DatabaseOutlined />
                                                <span>{dataset.name}</span>
                                            </>
                                        )
                                    },
                                    {
                                        title: (
                                            <>
                                                <ExperimentOutlined />
                                                <span>{task.name}</span>
                                            </>
                                        )
                                    }
                                ]}
                            />
                        </div>
                    </div>
                </div>
            </div>

            {/* 主要内容 */}
            <div className="main-content max-w-7xl mx-auto px-4 py-8">
                {/* 任务基本信息 */}
                <Card className="mb-6">
                    <Row align="middle">
                        <Col flex="auto">
                            <Space size="large">
                                <div className="inline-flex items-center justify-center w-12 h-12 bg-blue-100 rounded-lg">
                                    <ExperimentOutlined className="text-xl text-blue-600" />
                                </div>
                                <div>
                                    <Title level={3} className="mb-1">{task.name}</Title>
                                    <Space>
                                        <Tag color="blue">
                                            {task.type === 'detection' ? '病灶检测' :
                                                task.type === 'classification' ? '影像分类' : '图像分割'}
                                        </Tag>
                                        <Tag color={
                                            task.status === 'running' ? 'processing' :
                                                task.status === 'completed' ? 'success' :
                                                    task.status === 'error' ? 'error' : 'default'
                                        }>
                                            {task.status === 'running' ? '运行中' :
                                                task.status === 'completed' ? '已完成' :
                                                    task.status === 'error' ? '执行失败' : '就绪'}
                                        </Tag>
                                    </Space>
                                </div>
                            </Space>
                        </Col>
                        <Col>
                            <Space>
                                <Button
                                    type="primary"
                                    icon={<PlayCircleOutlined />}
                                    onClick={handleStartTask}
                                    disabled={task.status === 'running' || isProcessing}
                                    loading={task.status === 'running'}
                                >
                                    {task.status === 'running' ? '执行中...' : '开始任务'}
                                </Button>
                                {task.status === 'running' && (
                                    <Button
                                        danger
                                        icon={<StopOutlined />}
                                        onClick={() => setShowCancelModal(true)}
                                    >
                                        取消
                                    </Button>
                                )}
                                {task.status === 'completed' && taskResult && (
                                    <Button
                                        type="default"
                                        icon={<DownloadOutlined />}
                                    >
                                        下载结果
                                    </Button>
                                )}
                            </Space>
                        </Col>
                    </Row>
                </Card>

                {/* 主要内容区域 */}
                <Row gutter={[24, 24]}>
                    {/* 左侧：任务配置和状态 */}
                    <Col xs={24} lg={10}>
                        <Tabs
                            activeKey={activeTab}
                            onChange={setActiveTab}
                            items={[
                                {
                                    key: 'config',
                                    label: (
                                        <Space>
                                            <SettingOutlined />
                                            <span>参数配置</span>
                                        </Space>
                                    ),
                                    children: (
                                        <TaskParameterConfig
                                            task={task}
                                            onParametersChange={handleParametersChange}
                                            onConfigSave={handleConfigSave}
                                            disabled={task.status === 'running'}
                                        />
                                    )
                                },
                                {
                                    key: 'status',
                                    label: (
                                        <Space>
                                            <BarChartOutlined />
                                            <span>执行状态</span>
                                        </Space>
                                    ),
                                    children: (
                                        <TaskStatusDisplay
                                            task={task}
                                            onCancel={() => setShowCancelModal(true)}
                                            onRetry={handleRetryTask}
                                        />
                                    )
                                },
                                {
                                    key: 'results',
                                    label: (
                                        <Space>
                                            <FileTextOutlined />
                                            <span>执行结果</span>
                                        </Space>
                                    ),
                                    children: (
                                        <TaskResultDisplay
                                            task={task}
                                            results={taskResult}
                                        />
                                    ),
                                    disabled: !taskResult || taskResult.length === 0
                                }
                            ]}
                        />
                    </Col>

                    {/* 右侧：影像查看器 */}
                    <Col xs={24} lg={14}>
                        <Card
                            title="影像查看器"
                            className="h-full"
                            bodyStyle={{ padding: 0, height: 'calc(100vh - 200px)' }}
                        >
                            <div className="h-full flex items-center justify-center bg-gray-100">
                                {dataset.type === '3D' ? (
                                    <div className="text-center">
                                        <div className="grid grid-cols-2 gap-4 mb-4">
                                            <div className="w-48 h-36 bg-black border rounded flex items-center justify-center">
                                                <Typography.Text className="text-white">轴位 (Axial)</Typography.Text>
                                            </div>
                                            <div className="w-48 h-36 bg-black border rounded flex items-center justify-center">
                                                <Typography.Text className="text-white">矢状位 (Sagittal)</Typography.Text>
                                            </div>
                                            <div className="w-48 h-36 bg-black border rounded flex items-center justify-center">
                                                <Typography.Text className="text-white">冠状位 (Coronal)</Typography.Text>
                                            </div>
                                            <div className="w-48 h-36 bg-gray-200 border rounded flex items-center justify-center">
                                                <Typography.Text>控制面板</Typography.Text>
                                            </div>
                                        </div>
                                        <Typography.Text type="secondary">3D 影像查看器 - 等待后端数据</Typography.Text>
                                    </div>
                                ) : (
                                    <div className="text-center">
                                        <div className="flex space-x-4 mb-4">
                                            <div className="w-64 h-48 bg-black border rounded flex items-center justify-center">
                                                <Typography.Text className="text-white">主显示窗口</Typography.Text>
                                            </div>
                                            <div className="w-48 h-48 bg-gray-200 border rounded flex items-center justify-center">
                                                <Typography.Text>辅助窗口</Typography.Text>
                                            </div>
                                        </div>
                                        <Typography.Text type="secondary">2D 影像查看器 - 等待后端数据</Typography.Text>
                                    </div>
                                )}
                            </div>
                        </Card>
                    </Col>
                </Row>

                {/* 取消任务确认对话框 */}
                <Modal
                    title="确认取消任务"
                    open={showCancelModal}
                    onOk={handleCancelTask}
                    onCancel={() => setShowCancelModal(false)}
                    okText="确认取消"
                    cancelText="继续执行"
                    okButtonProps={{ danger: true }}
                >
                    <div className="flex items-start space-x-3">
                        <ExclamationCircleOutlined className="text-orange-500 text-xl mt-1" />
                        <div>
                            <p>确定要取消当前正在执行的任务吗？</p>
                            <p>取消后任务将停止执行，已处理的数据可能会丢失。</p>
                        </div>
                    </div>
                </Modal>
            </div>
        </div>
    )
}

export default TaskExecution